package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.pojo.Category;
import com.itheima.pojo.Dish;
import com.itheima.Dto.DishDto;
import com.itheima.pojo.DishFlavor;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    //添加菜品
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){

        dishService.saveWithFlavor(dishDto);
//        dishService.save(dishDto);


        //清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);

        return R.success("添加成功！");
    }

    //分页查询
    @GetMapping("/page")
    public R<Page> page(int page ,int pageSize, String name){

        Page<Dish> page1 = new Page<>(page,pageSize);

        Page<DishDto> dtoPage = new Page<>();

        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();

        wrapper.like(name!=null,Dish::getName,name);

        wrapper.orderByDesc(Dish::getCreateTime);

        dishService.page(page1,wrapper);

         BeanUtils.copyProperties(page1,dtoPage,"records");
        List<Dish> records = page1.getRecords();
        List<DishDto> list =  records.stream().map((item)->{
            DishDto dishDto = new DishDto();

           BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();
             dishService.getById(categoryId);
            Category category = categoryService.getById(categoryId);
            if (category!=null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;

        }).collect(Collectors.toList());
        dtoPage.setRecords(list);

        return R.success(page1);

    }


    //回显数据
    @GetMapping("/{id}")
    public R<Dish> getById(@PathVariable Long id){
//        Dish byId = dishService.getById(id);
        DishDto byId = dishService.getByIdWithFlavor(id);
        return R.success(byId);
    }


    //修改菜品
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
//        boolean b = dishService.updateById(dish);
        dishService.updateWithFlavor(dishDto);

        //清理所有菜品的缓存数据
        Set keys = redisTemplate.keys("dish_*"); //获取所有以dish_xxx开头的key
        redisTemplate.delete(keys); //删除这些key

        return R.success("修改成功！");
    }

    //删除菜品
//    @DeleteMapping
//    public R<String> deleteDish(@RequestParam DishDto dishDto){
//
//       dishService.deletedWithFlavor(dishDto);
//
//        return R.success("删除成功");
//    }

    //删除菜品+批量删除
    @DeleteMapping
    public R<String> deleteDish(@RequestParam List<Long> ids){


        dishService.deletedWithFlavor(ids);

        return R.success("删除成功");
    }

    //停售+起售
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable Integer status ,Long[] ids){

//        List<Long> longs = Arrays.asList(ids);

        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();

        wrapper.in(Dish::getId,ids);
        List<Dish> list = dishService.list(wrapper);


        int s=status==1 ? 1:0;

        for (Dish dish : list) {
            dish.setStatus(s);
            dishService.updateById(dish);
        }
        return R.success("操作成功！");

    }


//      根据分类id查询该分类下的所有菜品集合
        @GetMapping("/list")
        //修改和分类关联的dto
    public R<List<DishDto>> list(Dish dish){

        String dishRedisKey ="dish_"+ dish.getCategoryId();
            //先从redis中获取缓存数据
        List<DishDto>  DtoList = (List<DishDto>) redisTemplate.opsForValue().get(dishRedisKey);
            //判断如果redis不为空，则直接在redis中拿数据
         if (DtoList!=null){
            return R.success(DtoList);
         }

            LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        wrapper.eq(Dish::getStatus,1);
        wrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(wrapper);


//        return R.success(list);

        //修改
            List<DishDto> dishDtoList =  list.stream().map((item)->{
                DishDto dishDto = new DishDto();
                BeanUtils.copyProperties(item,dishDto);

                Long categoryId = item.getCategoryId();
                Category serviceById = categoryService.getById(categoryId);
                if (serviceById!=null){
                    String name = serviceById.getName();
                    dishDto.setCategoryName(name);
                }
                Long id = item.getId();
                LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(DishFlavor::getDishId,id);
                List<DishFlavor> flavorList = dishFlavorService.list(queryWrapper);
                    dishDto.setFlavors(flavorList);
                return dishDto;

            }).collect(Collectors.toList());

            //如果不存在，需要查询数据库，将查询到的菜品数据缓存到Redis
            redisTemplate.opsForValue().set(dishRedisKey,DtoList,60, TimeUnit.MINUTES);

            return R.success(dishDtoList);
    }



}
